<template>
  <div class="createPost-container">

    <el-form ref="postForm" :model="articledetail" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">

        <div align="right">
          <el-button v-loading="loading" style="margin-right: 10px; " type="success" @click="onSubmit">
            发布
          </el-button>
        </div>

      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="articledetail.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="60px" label="作者:" class="postInfo-container-item">
                    <el-input v-model="articledetail.author" style="width: 100px;" />

                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="100px" label="创建时间:">
                    <el-input v-model="articledetail.createTime" style="width: 200px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label-width="100px" label="浏览量:">
                    <el-input v-model="articledetail.clinkNum" style="width: 100px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label-width="100px" label="点赞数:">
                    <el-input v-model="articledetail.likesNum" style="width: 100px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label-width="100px" label="收藏数:">
                    <el-input v-model="articledetail.collectNum" style="width: 100px;" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>

                <el-col :span="6">
                  <el-form-item label-width="100px" label="类型:">
                    <el-input v-model="articledetail.type" style="width: 100px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="100px" label="更新时间:">
                    <el-input v-model="articledetail.updateTime" style="width: 200px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="100px" label="状态:">
                    <el-input v-model="articledetail.status" style="width: 200px;" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="100px" label="封面:">
                    <!-- <el-input v-model="articledetail.image" style="width: 200px;" /> -->

                    <!-- <div style="display:flex;flex-wrap: wrap;justify-content:Center">
                       <div v-if="articledetail.image!=''" style="position:relative;display:inline-block;">
                           <img style="width:80px;height:80px;" :src="articledetail.image">
                           <div @click="articledetail.image=''" style="cursor: pointer; position:absolute;
                            top:-10px;left:92%;background:red;
                            color:white;border-radius:50%;height:18px;width:18px;
                             font-weight:bold;text-align:center;line-height:18px">×</div>
                            </div>

                          <div v-if="articledetail.image==''" style="display:inline-block;">
                               <img style="width:60px;height:60px;margin:10px" @click="onPickFile2(itemIndex,list[itemIndex])" src="@/assets/add.jpeg">

                               <input id="upimg" type="file" ref="fileInput" accept="image/*" @change="getFile2" style="display: none;">
                          </div>
                    </div> -->
                    <div class="demo-image__preview">
                      <el-image
                        style="width: 100px; height: 100px"
                        :src="url"
                        :preview-src-list="srcList"
                      />
                    </div>

                  </el-form-item>

                </el-col>

              </el-row>

            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="概括:">
          <el-input
            v-model="articledetail.introduction"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="Please enter the content"
          />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="转载于:">
          <el-input
            v-model="articledetail.source"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="Please enter the content"
          />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="articledetail.content" :height="400" />
        </el-form-item>

        <!-- <el-form-item prop="image_uri" style="margin-bottom: 30px;">
					<Upload v-model="postForm.image_uri" />
				</el-form-item> -->
      </div>

    </el-form>

  </div>
</template>

<script>

import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import {
  validURL
} from '@/utils/validate'
import {
  fetchArticle
} from '@/api/article'
import {
  searchUser
} from '@/api/remote-search'
import Warning from './Warning'
import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown
} from './Dropdown'

const defaultForm = {
  status: 'draft',
  title: '', // 文章题目
  content: '', // 文章内容
  content_short: '', // 文章摘要
  source_uri: '', // 文章外链
  image_uri: '', // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  // platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}

export default {

  name: 'ArticleDetail',
  components: {
    Tinymce,
    MDinput,
    Upload,
    Sticky,
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  },
  // props: {
  // 	isEdit: {
  // 		type: Boolean,
  // 		default: false
  // 	}
  // },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {

      url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      srcList: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
      ],

      // preImg:'articledetail.image',
      postData: {
        		img: ''
      }, // 存放提交的图片
      articledetail: {},
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],

      rules: {
        image_uri: [{
          validator: validateRequire
        }],
        title: [{
          validator: validateRequire
        }],
        content: [{
          validator: validateRequire
        }],
        source_uri: [{
          validator: validateSourceUri,
          trigger: 'blur'
        }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return (+new Date(this.postForm.display_time))
      },
      set(val) {
        this.postForm.display_time = new Date(val)
      }
    }
  },
  created() {
    // if (this.isEdit) {
    //   const id = this.$route.params && this.$route.params.id
    //   this.fetchData(id)
    // }

    // this.tempRoute = Object.assign({}, this.$route)
    this.fetchDataById()
  },

  methods: {

    onSubmit() {
      var vm = this
      vm.articledetail.createTime = 1638175514000

      this.axios({
        method: 'PUT',
        url: 'http://172.21.136.71:8080/HealthyArticle',
        data: vm.articledetail,
        headers: {
          'Authorization': 'eyJKV1QiOiJKV1QiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiaWF0IjoxNjM2NDI4MDMxLCJqdGkiOiIzMmM0Y2JmYTZlOGE0Y2M4YjRkMDM1ODk3YjI5NzAyZiJ9.FLJnRiaw1oz8qgPZsuq8pINHeJNRf87bGE2uqN2akgc'
        }
      }).then(function(resp) {

      })
      vm.$router.go(-1)
    },

    fetchDataById() {
      var id = this.$route.params.articleId
      var vm = this
      this.axios({
        method: 'GET',
        url: 'http://172.21.136.71:8080/HealthyArticle/id?articleId=' + id,
        headers: {
          'Authorization': 'eyJKV1QiOiJKV1QiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiaWF0IjoxNjM2NDI4MDMxLCJqdGkiOiIzMmM0Y2JmYTZlOGE0Y2M4YjRkMDM1ODk3YjI5NzAyZiJ9.FLJnRiaw1oz8qgPZsuq8pINHeJNRf87bGE2uqN2akgc'
        }
      }).then(function(resp) {
        vm.articledetail = resp.data.data.article
        // 修改时间格式
        var dct = new Date(new Date(vm.articledetail.createTime).toString())
        vm.articledetail.createTime = dct.getFullYear() + '-' + (dct.getMonth() + 1) + '-' + dct
          .getDate() + ' ' + dct.getHours() + ':' + dct.getMinutes() + ':' + dct.getSeconds()
      })
    },
    setTagsViewTitle() {
      const title = 'Edit Article'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: '成功',
            message: '发布文章成功',
            type: 'success',
            duration: 2000
          })
          this.postForm.status = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    }
    // getRemoteUserList(query) {
    // 	searchUser(query).then(response => {
    // 		if (!response.data.items) return
    // 		this.userListOptions = response.data.items.map(v => v.name)
    // 	})
    // }
  }
}
</script>

<style lang="scss" scoped>
	@import "~@/styles/mixin.scss";

	.createPost-container {
		position: relative;

		.createPost-main-container {
			padding: 40px 45px 20px 50px;

			.postInfo-container {
				position: relative;
				@include clearfix;
				margin-bottom: 10px;

				.postInfo-container-item {
					float: left;
				}
			}
		}

		.word-counter {
			width: 40px;
			position: absolute;
			right: 10px;
			top: 0px;
		}
	}

	.article-textarea ::v-deep {
		textarea {
			padding-right: 40px;
			resize: none;
			border: none;
			border-radius: 0px;
			border-bottom: 1px solid #bfcbd9;
		}
	}
</style>
